package com.md24housecall.fragment;

import java.util.ArrayList;
import java.util.List;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.md24housecall.activity.PartnerDetailActivity;
import com.md24housecall.activity.R;
import com.md24housecall.adapter.PartnerCategoryAdapter;
import com.md24housecall.manager.CacheManager;
import com.md24housecall.manager.DimenManager;
import com.md24housecall.model.CategoryPartner;
import com.md24housecall.util.GlobalConstant;
import com.md24housecall.util.MyLog;
import com.md24housecall.view.PagingListView;
import com.md24housecall.view.PagingListView.PagingListViewListener;
import com.md24housecall.view.RatioImageView;
import com.md24housecall.view.RatioRelativeLayout;

public final class PartnerFragment extends android.support.v4.app.Fragment
		implements PagingListViewListener, OnItemClickListener {
	private static final String KEY_TAB_POSITION = "TestFragment:Position";
	private PagingListView lvCategoryPartner;
	private PartnerCategoryAdapter adapter;
	private List<CategoryPartner> listCategories = new ArrayList<CategoryPartner>();
	private int mTabPosition = 0;
	private RatioImageView mImgHeader;
	private RatioRelativeLayout mHeaderContainer;
	private Intent intentPartnerDetail;
	private View mainView;
	private boolean isPaging = true;
	private CacheManager cacheManager;
	private GlobalConstant constant=GlobalConstant.getInstance();
	private int start = 0;
	private int limit = constant.ITEMCATEGORY_NO;
	private int total = 0;
	private OnRefreshReceiver refreshDataBroadcast	= new OnRefreshReceiver();

	public static PartnerFragment newInstance(int tabPosition) {
		PartnerFragment fragment = new PartnerFragment();

		Bundle args = new Bundle();
		args.putInt(KEY_TAB_POSITION, tabPosition);
		fragment.setArguments(args);

		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getArguments() != null) {
			mTabPosition = getArguments().getInt(KEY_TAB_POSITION, 0);
		}
	}

	private void loadData() {
		total = cacheManager.getTotalPartnerCategory();
		MyLog.d(GlobalConstant.TAG, "count category: " + total);
		List<CategoryPartner> listCatgories=cacheManager.selectPartnerCategories(start, limit);
		if(listCatgories!=null && listCatgories.size()>0){
			MyLog.d(GlobalConstant.TAG, "select category: "
					+ listCatgories.size());
			for (CategoryPartner category : listCatgories) {
				listCategories.add(category);
			}
			adapter.notifyDataSetChanged();
		}
		if (total > listCategories.size()) {
			lvCategoryPartner.setPullLoadEnable(true);
			lvCategoryPartner.setPullRefreshEnable(true);
		} else {
			lvCategoryPartner.setPullLoadEnable(false);
			lvCategoryPartner.setPullRefreshEnable(true);
		}
	}

	private void initialize() {
		mImgHeader = (RatioImageView) mainView.findViewById(R.id.imgHeader);
		mImgHeader.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		mHeaderContainer = (RatioRelativeLayout) mainView
				.findViewById(R.id.header_container);
		mHeaderContainer.setRatio(DimenManager.WIDTH_TAB_HEADER_IMG,
				DimenManager.HEIGHT_TAB_HEADER_IMG);
		intentPartnerDetail = new Intent(getActivity(),
				PartnerDetailActivity.class);
		cacheManager = CacheManager.getInstance(getActivity());
		lvCategoryPartner = (PagingListView) mainView
				.findViewById(R.id.lvCategoryPartner);
		adapter = new PartnerCategoryAdapter(getActivity(), listCategories);
		lvCategoryPartner.setAdapter(adapter);
		if (isPaging) {
			lvCategoryPartner.setPullLoadEnable(true);
			lvCategoryPartner.setPullRefreshEnable(true);
			lvCategoryPartner.setPagingListViewListener(this);
		} else {
			lvCategoryPartner.setPullLoadEnable(false);
			lvCategoryPartner.setPullRefreshEnable(false);
		}
		lvCategoryPartner.setOnItemClickListener(this);
		IntentFilter filter = new IntentFilter(GlobalConstant.getInstance().ACTON_REFRESH);
		getActivity().registerReceiver(refreshDataBroadcast, filter);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.partner, container, false);
		mainView = v;
		try {
			initialize();
			loadData();
		} catch (Exception e) {
			// TODO: handle exception
			MyLog.d(GlobalConstant.TAG, "exception onCreateView PartnerFragment: "+e.getMessage());
		}
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_TAB_POSITION, mTabPosition);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		MyLog.d(GlobalConstant.TAG, "position partner category: "+position);
		intentPartnerDetail.putExtra(GlobalConstant.getInstance().KEYPARTNERDETAIL,listCategories.get(position - 1).getId());
		startActivity(intentPartnerDetail);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		start += constant.ITEMCATEGORY_NO;
//		limit += constant.ITEMCATEGORY_NO;
		loadData();		
		lvCategoryPartner.stopLoadMore();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		// getPartnerFromApi();
		refreshData();
		lvCategoryPartner.stopRefresh();
	}

	private void refreshData(){
		start = 0;
//		limit = constant.ITEMCATEGORY_NO;
		listCategories.clear();
		loadData();
	}
	private class OnRefreshReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			MyLog.d(GlobalConstant.TAG, "refresh category partner");
			refreshData();
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		if (refreshDataBroadcast != null) 
			getActivity().unregisterReceiver(refreshDataBroadcast);
		super.onDestroy();
	}
}
